<template>
  <div class="finance-detail-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="title">
        <h1>财务记录详情</h1>
        <span class="finance-no">财务单号：{{ financeRecord.financeNo }}</span>
      </div>
      <div class="action-buttons">
        <el-button @click="handleGoBack">
          <el-icon><ArrowLeft /></el-icon> 返回列表
        </el-button>
        <el-button type="primary" v-if="['pending'].includes(financeRecord.status)" @click="handleEdit">
          <el-icon><Edit /></el-icon> 编辑
        </el-button>
        <el-button type="success" v-if="['pending'].includes(financeRecord.status)" @click="handleApprove">
          <el-icon><Check /></el-icon> 审核通过
        </el-button>
        <el-button type="danger" v-if="['pending'].includes(financeRecord.status)" @click="handleReject">
          <el-icon><Close /></el-icon> 拒绝
        </el-button>
        <el-button type="warning" v-if="['pending', 'approved'].includes(financeRecord.status)" @click="handleCancel">
          <el-icon><RefreshLeft /></el-icon> 取消
        </el-button>
      </div>
    </div>

    <!-- 基本信息卡片 -->
    <el-row :gutter="20" class="info-row">
      <el-col :span="16">
        <el-card class="info-card">
          <div class="card-header">
            <h2>基本信息</h2>
          </div>
          <div class="info-content">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="财务单号">{{ financeRecord.financeNo }}</el-descriptions-item>
              <el-descriptions-item label="关联订单号">{{ financeRecord.orderNo }}</el-descriptions-item>
              <el-descriptions-item label="交易类型">
                <el-tag :type="financeRecord.type === 'income' ? 'success' : 'danger'">{{ financeRecord.type === 'income' ? '收入' : '支出' }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="供应商">{{ financeRecord.supplierName }}</el-descriptions-item>
              <el-descriptions-item label="交易日期">{{ financeRecord.transactionDate }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">
                <el-tag :type="getStatusTagType(financeRecord.status)">{{ getStatusText(financeRecord.status) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="交易金额" :span="3">
                <span class="amount-value" :class="financeRecord.type === 'income' ? 'text-success' : 'text-danger'">{{ financeRecord.amount > 0 ? '+' : '' }}{{ financeRecord.amount.toFixed(2) }} 元</span>
              </el-descriptions-item>
              <el-descriptions-item label="操作人">{{ financeRecord.operator }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ financeRecord.createTime }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ financeRecord.updateTime }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="3">{{ financeRecord.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>

      <!-- 支付信息卡片 -->
      <el-col :span="8">
        <el-card class="info-card">
          <div class="card-header">
            <h2>支付信息</h2>
          </div>
          <div class="payment-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="支付方式">{{ financeRecord.paymentMethod || '-' }}</el-descriptions-item>
              <el-descriptions-item label="银行账户">{{ financeRecord.bankAccount || '-' }}</el-descriptions-item>
              <el-descriptions-item label="银行名称">{{ financeRecord.bankName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="交易流水号">{{ financeRecord.transactionNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="支付时间">{{ financeRecord.paymentTime || '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 相关订单信息 -->
    <el-card class="related-order-card">
      <div class="card-header">
        <h2>相关订单信息</h2>
        <el-button type="text" @click="handleViewOrder">查看订单详情</el-button>
      </div>
      <div class="order-info">
        <el-table
          :data="[orderInfo]"
          border
          size="small"
          show-header
          :header-cell-style="{ 'background-color': '#f5f7fa' }"
        >
          <el-table-column prop="orderNo" label="订单号" min-width="140"></el-table-column>
          <el-table-column prop="supplierName" label="供应商" min-width="120"></el-table-column>
          <el-table-column prop="orderAmount" label="订单金额" min-width="110" align="right">
            <template #default="scope">{{ scope.row.orderAmount.toFixed(2) }} 元</template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getOrderStatusTagType(scope.row.orderStatus)">{{ scope.row.orderStatusText }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="140"></el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 操作历史 -->
    <el-card class="operation-history-card">
      <div class="card-header">
        <h2>操作历史</h2>
      </div>
      <div class="history-list">
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in operationHistory"
            :key="index"
            :timestamp="item.time"
            :placement="index % 2 === 0 ? 'top' : 'bottom'"
          >
            <el-card>
              <h4>{{ item.action }}</h4>
              <p class="operator-info">操作人：{{ item.operator }}</p>
              <p class="operation-content" v-if="item.content">{{ item.content }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ArrowLeft,
  Edit,
  Check,
  Close,
  RefreshLeft
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 路由实例
const router = useRouter();
const route = useRoute();

// 财务记录数据
const financeRecord = reactive<any>({
  id: '',
  financeNo: '',
  orderNo: '',
  supplierName: '',
  type: 'income',
  amount: 0,
  transactionDate: '',
  status: 'pending',
  operator: '',
  createTime: '',
  updateTime: '',
  remark: '',
  paymentMethod: '',
  bankAccount: '',
  bankName: '',
  transactionNo: '',
  paymentTime: ''
});

// 相关订单信息
const orderInfo = reactive<any>({
  orderNo: '',
  supplierName: '',
  orderAmount: 0,
  orderStatus: '',
  orderStatusText: '',
  createTime: ''
});

// 操作历史
const operationHistory = ref<any[]>([]);

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已审核',
    'rejected': '已拒绝',
    'cancelled': '已取消'
  };
  return statusMap[status] || '未知';
};

// 获取状态标签类型
const getStatusTagType = (status: string): string => {
  const typeMap = {
    'pending': 'info',
    'approved': 'success',
    'rejected': 'danger',
    'cancelled': 'warning'
  };
  return typeMap[status] || 'default';
};

// 获取订单状态标签类型
const getOrderStatusTagType = (status: number): string => {
  const typeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'processing',
    4: 'success',
    5: 'danger',
    6: 'warning'
  };
  return typeMap[status] || 'default';
};

// 返回列表
const handleGoBack = () => {
  router.push({ name: 'FinanceList' });
};

// 编辑财务记录
const handleEdit = () => {
  router.push({ name: 'FinanceEdit', params: { id: financeRecord.id } });
};

// 审核通过
const handleApprove = async () => {
  try {
    await ElMessageBox.confirm(`确定要审核通过财务记录 ${financeRecord.financeNo} 吗？`, '审核确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });

    // 模拟API请求
    setTimeout(() => {
      ElMessage.success('审核通过成功');
      // 更新状态
      financeRecord.status = 'approved';
      // 添加操作历史
      operationHistory.value.unshift({
        action: '审核通过',
        operator: '当前用户',
        time: new Date().toISOString().slice(0, 19).replace('T', ' '),
        content: '财务记录审核通过'
      });
    }, 800);
  } catch (error) {
    // 用户取消操作
  }
};

// 拒绝
const handleReject = async () => {
  try {
    const inputResult = await ElMessageBox.prompt(`请输入拒绝财务记录 ${financeRecord.financeNo} 的原因`, '拒绝确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入拒绝原因',
      type: 'warning'
    });

    const reason = inputResult.value.trim();
    if (!reason) {
      ElMessage.warning('拒绝原因不能为空');
      return;
    }

    // 模拟API请求
    setTimeout(() => {
      ElMessage.success('拒绝成功');
      // 更新状态
      financeRecord.status = 'rejected';
      // 添加操作历史
      operationHistory.value.unshift({
        action: '拒绝',
        operator: '当前用户',
        time: new Date().toISOString().slice(0, 19).replace('T', ' '),
        content: `拒绝原因：${reason}`
      });
    }, 800);
  } catch (error) {
    // 用户取消操作
  }
};

// 取消
const handleCancel = async () => {
  try {
    const inputResult = await ElMessageBox.prompt(`请输入取消财务记录 ${financeRecord.financeNo} 的原因`, '取消确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入取消原因',
      type: 'warning'
    });

    const reason = inputResult.value.trim();
    if (!reason) {
      ElMessage.warning('取消原因不能为空');
      return;
    }

    // 模拟API请求
    setTimeout(() => {
      ElMessage.success('取消成功');
      // 更新状态
      financeRecord.status = 'cancelled';
      // 添加操作历史
      operationHistory.value.unshift({
        action: '取消',
        operator: '当前用户',
        time: new Date().toISOString().slice(0, 19).replace('T', ' '),
        content: `取消原因：${reason}`
      });
    }, 800);
  } catch (error) {
    // 用户取消操作
  }
};

// 查看订单详情
const handleViewOrder = () => {
  router.push({ name: 'OrderDetail', params: { id: '1' } }); // 实际项目中应传入真实订单ID
};

// 获取财务记录详情
const getFinanceDetail = () => {
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    const isIncome = Math.random() > 0.4;
    const amount = Math.floor(Math.random() * 100000) + 10000;
    const statuses: ('pending' | 'approved' | 'rejected' | 'cancelled')[] = ['pending', 'approved', 'rejected', 'cancelled'];
    const statusIndex = Math.floor(Math.random() * statuses.length);
    const today = new Date();
    const createDate = new Date(today);
    createDate.setDate(today.getDate() - Math.floor(Math.random() * 10));
    const updateDate = new Date(createDate);
    updateDate.setDate(createDate.getDate() + Math.floor(Math.random() * 5));
    const transactionDate = new Date(createDate);
    transactionDate.setDate(createDate.getDate() + Math.floor(Math.random() * 3));

    // 设置财务记录数据
    Object.assign(financeRecord, {
      id: route.params.id as string,
      financeNo: `FIN${Date.now()}`,
      orderNo: `ZCY${Date.now() - 10000}`,
      supplierName: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      type: isIncome ? 'income' : 'expense',
      amount: isIncome ? amount : -amount,
      transactionDate: transactionDate.toISOString().slice(0, 10),
      status: statuses[statusIndex],
      operator: '张三',
      createTime: createDate.toISOString().slice(0, 19).replace('T', ' '),
      updateTime: updateDate.toISOString().slice(0, 19).replace('T', ' '),
      remark: '这是一条财务记录的详细备注信息，包含交易的具体说明和相关事项。',
      paymentMethod: '银行转账',
      bankAccount: '6222 **** **** 1234',
      bankName: '中国工商银行',
      transactionNo: `TR${Math.floor(Math.random() * 1000000000000)}`,
      paymentTime: transactionDate.toISOString().slice(0, 19).replace('T', ' ')
    });

    // 设置相关订单信息
    Object.assign(orderInfo, {
      orderNo: financeRecord.orderNo,
      supplierName: financeRecord.supplierName,
      orderAmount: Math.abs(financeRecord.amount) * (1 + Math.random() * 0.2),
      orderStatus: Math.floor(Math.random() * 5),
      orderStatusText: ['待确认', '已确认', '已发货', '已收货', '已完成'][Math.floor(Math.random() * 5)],
      createTime: new Date(createDate.getTime() - Math.random() * 86400000 * 5).toISOString().slice(0, 19).replace('T', ' ')
    });

    // 生成操作历史
    generateOperationHistory(statuses[statusIndex]);
  }, 800);
};

// 生成操作历史
const generateOperationHistory = (currentStatus: string) => {
  const history: any[] = [];
  const actions = [
    { action: '创建财务记录', content: '初始化财务记录信息' },
    { action: '编辑财务记录', content: '更新了交易金额和备注信息' }
  ];

  // 添加基础操作
  history.push(...actions);

  // 根据当前状态添加相应操作
  if (currentStatus === 'approved') {
    history.push({
      action: '审核通过',
      content: '财务记录审核通过'
    });
  } else if (currentStatus === 'rejected') {
    history.push({
      action: '拒绝',
      content: '拒绝原因：金额与订单不符'
    });
  } else if (currentStatus === 'cancelled') {
    history.push({
      action: '审核通过',
      content: '财务记录审核通过'
    }, {
      action: '取消',
      content: '取消原因：订单取消'
    });
  }

  // 设置时间和操作人
  const baseDate = new Date(financeRecord.createTime);
  operationHistory.value = history.map((item, index) => {
    const actionDate = new Date(baseDate);
    actionDate.setMinutes(baseDate.getMinutes() + index * 15);
    return {
      ...item,
      operator: ['张三', '李四', '王五'][Math.floor(Math.random() * 3)],
      time: actionDate.toISOString().slice(0, 19).replace('T', ' ')
    };
  }).reverse();
};

// 页面加载时获取数据
onMounted(() => {
  getFinanceDetail();
});
</script>

<style scoped lang="scss">
.finance-detail-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.title {
  display: flex;
  flex-direction: column;
}

.finance-no {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.info-row {
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.amount-value {
  font-size: 20px;
  font-weight: bold;
}

.related-order-card,
.operation-history-card {
  margin-bottom: 20px;
}

.order-info {
  overflow-x: auto;
}

.history-list {
  padding: 10px 0;
}

.el-timeline {
  padding-left: 20px;
}

.el-timeline-item {
  margin-bottom: 20px;
}

.el-timeline-item__timestamp {
  font-size: 14px;
}

.operation-content {
  margin-top: 5px;
  color: #606266;
  font-size: 14px;
}

.operator-info {
  color: #909399;
  font-size: 13px;
  margin-top: 3px;
}

.text-success {
  color: #67C23A;
}

.text-danger {
  color: #F56C6C;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .el-col {
    &.lg-16,
    &.lg-8 {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }
}

@media (max-width: 768px) {
  .finance-detail-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .action-buttons {
    flex-wrap: wrap;
    width: 100%;
  }

  .el-descriptions {
    :deep(.el-descriptions-item__content) {
      word-break: break-all;
    }
  }
}
</style>